package com.example.msi_pc.myweek11;

import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

public class MyIntentService extends IntentService {
    public MyIntentService(String name) {
        super(name);
    }
    public MyIntentService(){
        super("EmptyConstructor");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    //在Service开始时执行
    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        Log.d("MyIntentService","新任务"+startId+"即将运行");
        //将必要的信息加入Intent,以便于传送给onHandleIntent()方法处理
        intent.putExtra("startId",startId);
        return super.onStartCommand(intent,flags,startId);
    }
    //在onHandleIntent()中实现要执行的耗时操作
    @Override
    protected void onHandleIntent(@Nullable Intent intent){
        //获取任务开始时在Intent中提供的有关信息
        int startId=intent.getIntExtra("startId",0);
        for(int i=0;i<5;i++){
            //在日志中将能查看启动多个服务任务后，多项耗时任务的交叉执行
            Log.d("MyIntentService","任务"+startId+"正在运行："+i);
            //用线程休眠的操作代表耗时操作，可换为实际的计算、下载等真正的耗时操作
            try{
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Log.d("MyIntentService","任务"+startId+"运行结束");
    }
}